<template>
  <div>
    <el-container id="container">
      <el-header>
        <span style="font-size:14px">图书关键词：</span>
        <el-input size="medium" class="keywordInput" v-model="keyword" clearable @clear="clearKeyword"></el-input>
        <span style="font-size:14px;margin-left:20px">图书状态：</span>
        <el-select size="medium" v-model="selectStatus" clearable @clear="clearSelection">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-button style="margin-left:20px" size="medium" @click="searchBook" type="primary" plain>搜索</el-button>
        <el-button size="medium" type="primary" style="margin-left:260px" @click="openAddForm">添加图书</el-button>
      </el-header>
      <el-main>
        <el-table height="415" border style="width: 100%" :data="bookList">
          <el-table-column prop="bookId" label="图书ID" width="100">
          </el-table-column>
          <el-table-column prop="bookName" label="图书名" width="200">
          </el-table-column>
          <el-table-column prop="author" label="作者" width="130">
          </el-table-column>
          <el-table-column prop="publishCompany" label="出版社">
          </el-table-column>
          <el-table-column prop="bookStatus" label="图书状态" width="140">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.bookStatus===1" type="success">已上架</el-tag>
              <el-tag v-if="scope.row.bookStatus===0" type="danger">未上架</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="currentPrice" label="现价" width="100">
          </el-table-column>
          <el-table-column label="操作" width="230">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="getBookDetails(scope.row)">详情</el-button>
              <el-button type="warning" size="mini" @click="openEditBookMsg(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.bookStatus===0" type="success" size="mini"
                @click="updateBookStatus(scope.row.bookId,'上架')">上架
              </el-button>
              <el-button v-if="scope.row.bookStatus===1" type="danger" size="mini"
                @click="updateBookStatus(scope.row.bookId,'下架')">下架
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="margin-top:20px" background layout="prev, pager, next" :total="bookListTotal"
          :page-size="getBookListParams.pageSize" :pager-count="5" @current-change="pageChange"
          :current-page="getBookListParams.page">
        </el-pagination>
      </el-main>
    </el-container>
    <!-- 图书详情弹出框 -->
    <el-dialog title="图书详情" :visible.sync="detailsDialogFlag" width="40%" modal-append-to-body append-to-body>
      <el-tabs tab-position="left" style="height: 200px;">
        <el-tab-pane label="图片预览">
          <el-image style="width: 150px; height: 200px" :src="this.bookDetails.imgurl" fit="fit"></el-image>
        </el-tab-pane>
        <el-tab-pane label="图书简介">
          <p id="introduction">{{this.bookDetails.info}}</p>
        </el-tab-pane>
        <el-tab-pane label="图片参数">
          <el-form id="detailsForm" ref="detailsForm" :model="bookDetails" label-width="80px">
            <el-form-item label="出版日期:" class="detailFormItem">
              <span>{{this.bookDetails.publishDate}}</span>
              <!-- <el-input v-model="bookDetails.publishDate" disabled></el-input> -->
            </el-form-item>
            <el-form-item label="图书原价:" class="detailFormItem">
              <span>{{this.bookDetails.originalPrice}} 元</span>
              <!--  <el-input v-model="bookDetails.originalPrice" disabled></el-input> -->
            </el-form-item>
            <el-form-item label="图书库存:" class="detailFormItem">
              <span>{{this.bookDetails.inventoryNum}} 件</span>
              <!--  <el-input v-model="bookDetails.inventoryNum" disabled></el-input> -->
            </el-form-item>
            <el-form-item label="图书销量:" class="detailFormItem">
              <span>{{this.bookDetails.saleNum}} 件</span>
              <!--  <el-input v-model="bookDetails.saleNum" disabled></el-input> -->
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 编辑图书弹出框 -->
    <el-dialog title="编辑图书" :visible.sync="editDialogFlag" width="40%" modal-append-to-body append-to-body
      @close="closeEditForm">
      <el-form id="detailsForm" ref="editForm" :model="editBookForm" :rules="rules" label-width="80px">
        <el-form-item label="图书名" prop="bookName">
          <el-input v-model="editBookForm.bookName"></el-input>
        </el-form-item>
        <el-form-item label="图书现价" prop="currentPrice">
          <el-input v-model="editBookForm.currentPrice"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publishCompany">
          <el-input v-model="editBookForm.publishCompany"></el-input>
        </el-form-item>
        <el-form-item label="图书作者" prop="author">
          <el-input v-model="editBookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="图书简介" prop="info">
          <el-input type="textarea" :rows="5" v-model="editBookForm.info"></el-input>
        </el-form-item>
        <el-form-item label="图书库存" prop="">
          <el-input v-model="editBookForm.inventoryNum"></el-input>
        </el-form-item>
        <el-form-item label="图书销量" prop="">
          <el-input v-model="editBookForm.saleNum" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogFlag = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditBookMsg">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加图书弹出框 -->
    <el-dialog title="添加图书" :visible.sync="addDialogFlag" width="30%" modal-append-to-body append-to-body
      @close="closeAddForm">
      <el-form ref="addForm" :model="addBookForm" :rules="rules" label-width="80px">
        <el-form-item label="上传图片">
          <el-upload class="upload-demo" ref="upload" :action="uploadAction" :file-list="fileList" :auto-upload="false"
            :on-success="uploadSuccess" :data="uploadParms" :on-error="uploadError" :on-progress="uploadProgress"
            :on-change="uploadChange" :multiple="false" :limit=1 :on-exceed="uploadExceed">
            <el-button slot="trigger" size="small" type="primary">选取图片文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="图书名" prop="bookName">
          <el-input v-model="addBookForm.bookName"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="addBookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="一级分类" prop="firstTypeId">
          <el-select style="width:100%" @change="changeFirstType" size="medium" v-model="addBookForm.firstTypeId"
            clearable placeholder="请选择" @clear="cleardFirstType">
            <el-option v-for="item in firstTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="secondTypeId">
          <el-select style="width:100%" size="medium" v-model="addBookForm.secondTypeId" clearable placeholder="请选择"
            :disabled=secondTypeSelectionFlag>
            <el-option v-for="item in secondTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出版社" prop="publishCompany">
          <el-input v-model="addBookForm.publishCompany"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker style="width:100%" size="large" align="center" v-model="addBookForm.publishDate" type="date"
            placeholder="选择日期">
          </el-date-picker>
          <!-- <el-input v-model="addBookForm.publishDate"></el-input> -->
        </el-form-item>
        <el-form-item label="图书库存" prop="inventoryNum">
          <el-input v-model="addBookForm.inventoryNum"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogFlag = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      rules: {
        bookName: [
          { required: true, message: '请输入图书名', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者名', trigger: 'blur' }
        ],
        info: [
          { required: true, message: '请输入图书简介', trigger: 'blur' }
        ],
        currentPrice: [
          { required: true, message: '请输入图书价格', trigger: 'blur' }
        ],
        publishCompany: [
          { required: true, message: '请输入出版社', trigger: 'blur' }
        ],
        publishDate: [
          { required: true, message: '请输入出版日期', trigger: 'blur' }
        ],
        inventoryNum: [
          { required: true, message: '请输入图书库存量', trigger: 'blur' }
        ],
        firstTypeId: [
          { required: true, message: '请选择一级分类', trigger: 'change' }
        ],
        secondTypeId: [
          { required: true, message: '请选择二级分类', trigger: 'change' }
        ]
      },
      options: [
        {
          value: 0,
          label: '未上架'
        },
        {
          value: 1,
          label: '已上架'
        }
      ],
      selectStatus: '不限',
      keyword: '不限',
      getBookListParams: {
        page: 1,
        pageSize: 1,
        keyword: ''
      },
      bookList: [],
      bookDetails: {

      },
      editBookForm: {
        bookId: 0,
        bookName: '',
        currentPrice: 0,
        info: '',
        publishCompany: '',
        author: '',
        saleNum: 0,
        inventoryNum: 0
      },
      addBookForm: {
        image: 'https://ddbookshop-img.oss-cn-shenzhen.aliyuncs.com',
        bookName: '',
        publishCompany: '',
        author: '',
        publishDate: '',
        inventoryNum: 0,
        firstTypeId: '',
        secondTypeId: ''
      },
      bookListTotal: 0,
      detailsDialogFlag: false,
      editDialogFlag: false,
      addDialogFlag: false,
      fileList: [

      ],
      uploadParms: {
        key: 'img',
        success_action_status: 200
      },
      uploadAction: 'http://ddbookshop-img.oss-cn-shenzhen.aliyuncs.com',
      firstTypeList: [

      ],
      secondTypeList: [

      ],
      secondTypeSelectionFlag: true
    }
  },
  methods: {
    clearKeyword: function () {
      this.keyword = '不限'
    },
    clearSelection: function () {
      this.selectStatus = '不限'
    },
    searchBook: function () {
      if (!(this.keyword === '不限')) {
        this.getBookListParams.keyword = this.keyword
      } else {
        this.getBookListParams.keyword = ''
      }
      if (!(this.selectStatus === '不限')) {
        this.getBookListParams.status = parseInt(this.selectStatus)
        console.log(this.getBookListParams.status)
      } else {
        this.$delete(this.getBookListParams, 'status')
      }
      this.getBookList()
    },
    getBookList: async function () {
      const res = await this.$axios({
        method: 'get',
        url: '/back/book',
        params: this.getBookListParams
      })
      this.bookList = res.data.data.list // 获取数据
      this.bookListTotal = res.data.data.total // 获取总数
    },
    pageChange: function (newpage) {
      this.getBookListParams.page = newpage
      this.getBookList()
    },
    getBookDetails: function (row) {
      this.bookDetails.info = row.info
      this.bookDetails.imgurl = row.image
      this.bookDetails.publishDate = row.publishDate
      this.bookDetails.inventoryNum = row.inventoryNum
      this.bookDetails.saleNum = row.saleNum
      this.bookDetails.originalPrice = row.originalPrice
      this.detailsDialogFlag = true
    },
    openEditBookMsg: function (row) {
      this.editBookForm.bookId = row.bookId
      this.editBookForm.bookName = row.bookName
      this.editBookForm.currentPrice = row.currentPrice
      this.editBookForm.info = row.info
      this.editBookForm.publishCompany = row.publishCompany
      this.editBookForm.author = row.author
      this.editBookForm.saleNum = row.saleNum
      this.editBookForm.inventoryNum = row.inventoryNum
      this.editDialogFlag = true
    },
    closeEditForm: function () {
      this.$refs.editForm.clearValidate()
    },
    confirmEditBookMsg: async function () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          this.$message.error('请正确完整填写表单')
        } else {
          const res = await this.$axios({
            method: 'put',
            url: '/back/book',
            data: this.editBookForm
          })
          if (res.data.code === 200) {
            this.$message.success('修改图书信息成功')
            this.getBookList()
          } else {
            this.$message.error('修改图书信息失败')
          }
          this.editDialogFlag = false
        }
      })
    },
    updateBookStatus: function (id, msg) {
      this.$confirm('是否确定将该书籍' + msg + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const bookRes = await this.$axios.get('/back/book/' + id)
        const book = bookRes.data.data
        if (book.info === null || book.currentPrice === null) {
          this.$message.warning('该书籍存在字段为空的值, 请先编辑')
        } else {
          const res = await this.$axios.delete('/back/book/' + id)
          if (res.data.code === 200) {
            this.$message.success('修改图书状态成功')
            this.getBookList()
          } else {
            this.$message.error('操作失败')
          }
        }
      })
    },
    getFirstTypeList: async function () {
      const res = await this.$axios.get('/back/booktype')
      res.data.data.forEach((value, index) => {
        this.firstTypeList.push(res.data.data[index].booktype)
      })
    },
    changeFirstType: function () {
      this.secondTypeSelectionFlag = false
      this.getSecondTypeList(this.addBookForm.firstTypeId)
    },
    getSecondTypeList: async function (firstId) {
      const res = await this.$axios('/back/booktype/' + firstId)
      this.secondTypeList = res.data.data
    },
    openAddForm: function () {
      this.getFirstTypeList()
      this.addDialogFlag = true
    },
    closeAddForm: function () {
      this.$refs.addForm.resetFields()
      this.firstTypeList = []
      this.secondTypeList = []
      this.addBookForm.inventoryNum = 0
      this.addBookForm = {}
      this.fileList = []
      this.addDialogFlag = false
    },
    cleardFirstType: function () {
      this.secondTypeSelectionFlag = true
      this.addBookForm.secondTypeId = ''
    },
    submitUpload: function () {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择需要上传的图片文件')
        return
      }
      this.$refs.addForm.validate(valid => {
        if (!valid) {
          this.$message.error('请正确完整填写表单')
        } else {
          this.$refs.upload.submit()
        }
      })
    },
    uploadChange: function (file, fileList) {
      this.fileList = fileList
      this.uploadParms.key = file.name
    },
    uploadExceed: function () {
      this.$message.warning('只允许上传一张图片')
    },
    uploadSuccess: async function (response, file, fileList) {
      this.$message({
        message: '图片文件上传成功！',
        type: 'success',
        duration: 1800
      })
      this.addBookForm.image = this.addBookForm.image + '/' + file.name
      this.confirmAddBook()
    },
    uploadProgress: function () {
      this.$message({
        message: '图片文件上传中',
        duration: 800
      })
    },
    uploadError: function () {
      this.$message.error('图片文件上传失败...')
    },
    confirmAddBook: async function () {
      const res = await this.$axios({
        method: 'post',
        url: '/back/book',
        data: this.addBookForm
      })
      if (res.data.code === 200) {
        this.$message.success('添加图书成功')
        this.closeAddForm()
        this.getBookList()
      } else {
        this.$message.error('添加图书失败')
      }
    }
  },
  created: function () {
    this.getBookList()
  },
  mounted: function () {

  }
}
</script>

<style lang="less" scoped>
html,
body,
#app {
  background-color: #e6e6e6;
  height: 100%;
  margin: 0;
  padding: 0;
}
.keywordInput {
  width: 20%;
}
#introduction {
  font-size: 16px;
  padding: 25px;
  margin-top: 0px;
}
#pane-0 {
  text-align: center;
}
.detailFormItem {
  margin: 5px;
}
</style>
